4 * Created on Sep 24, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ('ApiQueryBase.php');
32 * This class contains a list of pages that the client has requested.
33 * Initially, when the client passes in titles=, pageids=, or revisions= parameter,
34 * an instance of the ApiPageSet class will normalize titles,
35 * determine if the pages/revisions exist, and prefetch any additional data page data requested.
37 * When generator is used, the result of the generator will become the input for the
38 * second instance of this class, and all subsequent actions will go use the second instance
43 class ApiPageSet
extends ApiQueryBase
{
45 private $mAllPages; // [ns][dbkey] => page_id or 0 when missing
46 private $mTitles, $mGoodTitles, $mMissingTitles, $mMissingPageIDs, $mRedirectTitles;
47 private $mNormalizedTitles, $mInterwikiTitles;
48 private $mResolveRedirects, $mPendingRedirectIDs;
49 private $mGoodRevIDs, $mMissingRevIDs;
52 private $mRequestedPageFields;
54 public function __construct($query, $resolveRedirects = false) {
55 parent
:: __construct($query, __CLASS__
);
57 $this->mAllPages
= array ();
58 $this->mTitles
= array();
59 $this->mGoodTitles
= array ();
60 $this->mMissingTitles
= array ();
61 $this->mMissingPageIDs
= array ();
62 $this->mRedirectTitles
= array ();
63 $this->mNormalizedTitles
= array ();
64 $this->mInterwikiTitles
= array ();
65 $this->mGoodRevIDs
= array();
66 $this->mMissingRevIDs
= array();
68 $this->mRequestedPageFields
= array ();
69 $this->mResolveRedirects
= $resolveRedirects;
71 $this->mPendingRedirectIDs
= array();
73 $this->mFakePageId
= -1;
76 public function isResolvingRedirects() {
77 return $this->mResolveRedirects
;
80 public function requestField($fieldName) {
81 $this->mRequestedPageFields
[$fieldName] = null;
84 public function getCustomField($fieldName) {
85 return $this->mRequestedPageFields
[$fieldName];
89 * Get fields that modules have requested from the page table
91 public function getPageTableFields() {
92 // Ensure we get minimum required fields
95 'page_namespace' => null,
99 // only store non-default fields
100 $this->mRequestedPageFields
= array_diff_key($this->mRequestedPageFields
, $pageFlds);
102 if ($this->mResolveRedirects
)
103 $pageFlds['page_is_redirect'] = null;
105 $pageFlds = array_merge($pageFlds, $this->mRequestedPageFields
);
106 return array_keys($pageFlds);
110 * Returns an array [ns][dbkey] => page_id for all requested titles
111 * page_id is a unique negative number in case title was not found
113 public function getAllTitlesByNamespace() {
114 return $this->mAllPages
;
118 * All Title objects provided.
119 * @return array of Title objects
121 public function getTitles() {
122 return $this->mTitles
;
126 * Returns the number of unique pages (not revisions) in the set.
128 public function getTitleCount() {
129 return count($this->mTitles
);
133 * Title objects that were found in the database.
134 * @return array page_id (int) => Title (obj)
136 public function getGoodTitles() {
137 return $this->mGoodTitles
;
141 * Returns the number of found unique pages (not revisions) in the set.
143 public function getGoodTitleCount() {
144 return count($this->mGoodTitles
);
148 * Title objects that were NOT found in the database.
149 * The array's index will be negative for each item
150 * @return array of Title objects
152 public function getMissingTitles() {
153 return $this->mMissingTitles
;
157 * Page IDs that were not found in the database
158 * @return array of page IDs
160 public function getMissingPageIDs() {
161 return $this->mMissingPageIDs
;
165 * Get a list of redirects when doing redirect resolution
166 * @return array prefixed_title (string) => prefixed_title (string)
168 public function getRedirectTitles() {
169 return $this->mRedirectTitles
;
173 * Get a list of title normalizations - maps the title given
174 * with its normalized version.
175 * @return array raw_prefixed_title (string) => prefixed_title (string)
177 public function getNormalizedTitles() {
178 return $this->mNormalizedTitles
;
182 * Get a list of interwiki titles - maps the title given
183 * with to the interwiki prefix.
184 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
186 public function getInterwikiTitles() {
187 return $this->mInterwikiTitles
;
191 * Get the list of revision IDs (requested with revids= parameter)
192 * @return array revID (int) => pageID (int)
194 public function getRevisionIDs() {
195 return $this->mGoodRevIDs
;
199 * Revision IDs that were not found in the database
200 * @return array of revision IDs
202 public function getMissingRevisionIDs() {
203 return $this->mMissingRevIDs
;
207 * Returns the number of revisions (requested with revids= parameter)
209 public function getRevisionCount() {
210 return count($this->getRevisionIDs());
214 * Populate from the request parameters
216 public function execute() {
218 $titles = $pageids = $revids = null;
219 extract($this->extractRequestParams());
221 // Only one of the titles/pageids/revids is allowed at the same time
224 $dataSource = 'titles';
225 if (isset ($pageids)) {
226 if (isset ($dataSource))
227 $this->dieUsage("Cannot use 'pageids' at the same time as '$dataSource'", 'multisource');
228 $dataSource = 'pageids';
230 if (isset ($revids)) {
231 if (isset ($dataSource))
232 $this->dieUsage("Cannot use 'revids' at the same time as '$dataSource'", 'multisource');
233 $dataSource = 'revids';
236 switch ($dataSource) {
238 $this->initFromTitles($titles);
241 $this->initFromPageIds($pageids);
244 if($this->mResolveRedirects
)
245 $this->dieUsage('revids may not be used with redirect resolution', 'params');
246 $this->initFromRevIDs($revids);
249 // Do nothing - some queries do not need any of the data sources.
256 * Initialize PageSet from a list of Titles
258 public function populateFromTitles($titles) {
260 $this->initFromTitles($titles);
265 * Initialize PageSet from a list of Page IDs
267 public function populateFromPageIDs($pageIDs) {
269 $this->initFromPageIds($pageIDs);
274 * Initialize PageSet from a rowset returned from the database
276 public function populateFromQueryResult($db, $queryResult) {
278 $this->initFromQueryResult($db, $queryResult);
283 * Initialize PageSet from a list of Revision IDs
285 public function populateFromRevisionIDs($revIDs) {
287 $revIDs = array_map('intval', $revIDs); // paranoia
288 $this->initFromRevIDs($revIDs);
293 * Extract all requested fields from the row received from the database
295 public function processDbRow($row) {
297 // Store Title object in various data structures
298 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
300 // skip any pages that user has no rights to read
301 if ($title->userCanRead()) {
303 $pageId = intval($row->page_id
);
304 $this->mAllPages
[$row->page_namespace
][$row->page_title
] = $pageId;
305 $this->mTitles
[] = $title;
307 if ($this->mResolveRedirects
&& $row->page_is_redirect
== '1') {
308 $this->mPendingRedirectIDs
[$pageId] = $title;
310 $this->mGoodTitles
[$pageId] = $title;
313 foreach ($this->mRequestedPageFields
as $fieldName => & $fieldValues)
314 $fieldValues[$pageId] = $row-> $fieldName;
318 public function finishPageSetGeneration() {
320 $this->resolvePendingRedirects();
325 * This method populates internal variables with page information
326 * based on the given array of title strings.
329 * #1 For each title, get data from `page` table
330 * #2 If page was not found in the DB, store it as missing
332 * Additionally, when resolving redirects:
333 * #3 If no more redirects left, stop.
334 * #4 For each redirect, get its links from `pagelinks` table.
335 * #5 Substitute the original LinkBatch object with the new list
336 * #6 Repeat from step #1
338 private function initFromTitles($titles) {
340 // Get validated and normalized title objects
341 $linkBatch = $this->processTitlesArray($titles);
342 if($linkBatch->isEmpty())
345 $db = $this->getDB();
346 $set = $linkBatch->constructSet('page', $db);
348 // Get pageIDs data from the `page` table
349 $this->profileDBIn();
350 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
351 $this->profileDBOut();
353 // Hack: get the ns:titles stored in array(ns => array(titles)) format
354 $this->initFromQueryResult($db, $res, $linkBatch->data
, true); // process Titles
356 // Resolve any found redirects
357 $this->resolvePendingRedirects();
360 private function initFromPageIds($pageids) {
364 $pageids = array_map('intval', $pageids); // paranoia
366 'page_id' => $pageids
369 $db = $this->getDB();
371 // Get pageIDs data from the `page` table
372 $this->profileDBIn();
373 $res = $db->select('page', $this->getPageTableFields(), $set, __METHOD__
);
374 $this->profileDBOut();
376 $this->initFromQueryResult($db, $res, array_flip($pageids), false); // process PageIDs
378 // Resolve any found redirects
379 $this->resolvePendingRedirects();
383 * Iterate through the result of the query on 'page' table,
384 * and for each row create and store title object and save any extra fields requested.
385 * @param $db Database
386 * @param $res DB Query result
387 * @param $remaining Array of either pageID or ns/title elements (optional).
388 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
389 * @param $processTitles bool Must be provided together with $remaining.
390 * If true, treat $remaining as an array of [ns][title]
391 * If false, treat it as an array of [pageIDs]
392 * @return Array of redirect IDs (only when resolving redirects)
394 private function initFromQueryResult($db, $res, &$remaining = null, $processTitles = null) {
395 if (!is_null($remaining) && is_null($processTitles))
396 ApiBase
:: dieDebug(__METHOD__
, 'Missing $processTitles parameter when $remaining is provided');
398 while ($row = $db->fetchObject($res)) {
400 $pageId = intval($row->page_id
);
402 // Remove found page from the list of remaining items
403 if (isset($remaining)) {
405 unset ($remaining[$row->page_namespace
][$row->page_title
]);
407 unset ($remaining[$pageId]);
410 // Store any extra fields requested by modules
411 $this->processDbRow($row);
413 $db->freeResult($res);
415 if(isset($remaining)) {
416 // Any items left in the $remaining list are added as missing
418 // The remaining titles in $remaining are non-existant pages
419 foreach ($remaining as $ns => $dbkeys) {
420 foreach ( $dbkeys as $dbkey => $unused ) {
421 $title = Title
:: makeTitle($ns, $dbkey);
422 $this->mAllPages
[$ns][$dbkey] = $this->mFakePageId
;
423 $this->mMissingTitles
[$this->mFakePageId
] = $title;
424 $this->mFakePageId
--;
425 $this->mTitles
[] = $title;
431 // The remaining pageids do not exist
432 if(empty($this->mMissingPageIDs
))
433 $this->mMissingPageIDs
= array_keys($remaining);
435 $this->mMissingPageIDs
= array_merge($this->mMissingPageIDs
, array_keys($remaining));
440 private function initFromRevIDs($revids) {
445 $db = $this->getDB();
447 $remaining = array_flip($revids);
449 $tables = array('revision');
450 $fields = array('rev_id','rev_page');
451 $where = array('rev_deleted' => 0, 'rev_id' => $revids);
453 // Get pageIDs data from the `page` table
454 $this->profileDBIn();
455 $res = $db->select( $tables, $fields, $where, __METHOD__
);
456 while ( $row = $db->fetchObject( $res ) ) {
457 $revid = intval($row->rev_id
);
458 $pageid = intval($row->rev_page
);
459 $this->mGoodRevIDs
[$revid] = $pageid;
460 $pageids[$pageid] = '';
461 unset($remaining[$revid]);
463 $db->freeResult( $res );
464 $this->profileDBOut();
466 $this->mMissingRevIDs
= array_keys($remaining);
468 // Populate all the page information
469 if($this->mResolveRedirects
)
470 ApiBase
:: dieDebug(__METHOD__
, 'revids may not be used with redirect resolution');
471 $this->initFromPageIds(array_keys($pageids));
474 private function resolvePendingRedirects() {
476 if($this->mResolveRedirects
) {
477 $db = $this->getDB();
478 $pageFlds = $this->getPageTableFields();
480 // Repeat until all redirects have been resolved
481 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
482 while (!empty ($this->mPendingRedirectIDs
)) {
484 // Resolve redirects by querying the pagelinks table, and repeat the process
485 // Create a new linkBatch object for the next pass
486 $linkBatch = $this->getRedirectTargets();
488 if ($linkBatch->isEmpty())
491 $set = $linkBatch->constructSet('page', $db);
495 // Get pageIDs data from the `page` table
496 $this->profileDBIn();
497 $res = $db->select('page', $pageFlds, $set, __METHOD__
);
498 $this->profileDBOut();
500 // Hack: get the ns:titles stored in array(ns => array(titles)) format
501 $this->initFromQueryResult($db, $res, $linkBatch->data
, true);
506 private function getRedirectTargets() {
508 $linkBatch = new LinkBatch();
509 $db = $this->getDB();
511 // find redirect targets for all redirect pages
512 $this->profileDBIn();
513 $res = $db->select('pagelinks', array (
518 'pl_from' => array_keys($this->mPendingRedirectIDs
520 $this->profileDBOut();
522 while ($row = $db->fetchObject($res)) {
524 $plfrom = intval($row->pl_from
);
526 // Bug 7304 workaround
527 // ( http://bugzilla.wikipedia.org/show_bug.cgi?id=7304 )
528 // A redirect page may have more than one link.
529 // This code will only use the first link returned.
530 if (isset ($this->mPendingRedirectIDs
[$plfrom])) { // remove line when bug 7304 is fixed
532 $titleStrFrom = $this->mPendingRedirectIDs
[$plfrom]->getPrefixedText();
533 $titleStrTo = Title
:: makeTitle($row->pl_namespace
, $row->pl_title
)->getPrefixedText();
534 unset ($this->mPendingRedirectIDs
[$plfrom]); // remove line when bug 7304 is fixed
536 // Avoid an infinite loop by checking if we have already processed this target
537 if (!isset ($this->mAllPages
[$row->pl_namespace
][$row->pl_title
])) {
538 $linkBatch->add($row->pl_namespace
, $row->pl_title
);
541 // This redirect page has more than one link.
542 // This is very slow, but safer until bug 7304 is resolved
543 $title = Title
:: newFromID($plfrom);
544 $titleStrFrom = $title->getPrefixedText();
546 $article = new Article($title);
547 $text = $article->getContent();
548 $titleTo = Title
:: newFromRedirect($text);
549 $titleStrTo = $titleTo->getPrefixedText();
551 if (is_null($titleStrTo))
552 ApiBase
:: dieDebug(__METHOD__
, 'Bug7304 workaround: redir target from {$title->getPrefixedText()} not found');
554 // Avoid an infinite loop by checking if we have already processed this target
555 if (!isset ($this->mAllPages
[$titleTo->getNamespace()][$titleTo->getDBkey()])) {
556 $linkBatch->addObj($titleTo);
560 $this->mRedirectTitles
[$titleStrFrom] = $titleStrTo;
562 $db->freeResult($res);
564 // All IDs must exist in the page table
565 if (!empty($this->mPendingRedirectIDs
[$plfrom]))
566 ApiBase
:: dieDebug(__METHOD__
, 'Invalid redirect IDs were found');
572 * Given an array of title strings, convert them into Title objects.
573 * Alternativelly, an array of Title objects may be given.
574 * This method validates access rights for the title,
575 * and appends normalization values to the output.
577 * @return LinkBatch of title objects.
579 private function processTitlesArray($titles) {
581 $linkBatch = new LinkBatch();
583 foreach ($titles as $title) {
585 $titleObj = is_string($title) ? Title
:: newFromText($title) : $title;
587 $this->dieUsage("bad title $titleString", 'invalidtitle');
589 $iw = $titleObj->getInterwiki();
591 // This title is an interwiki link.
592 $this->mInterwikiTitles
[$titleObj->getPrefixedText()] = $iw;
596 if ($titleObj->getNamespace() < 0)
597 $this->dieUsage("No support for special page $titleString has been implemented", 'unsupportednamespace');
598 if (!$titleObj->userCanRead())
599 $this->dieUsage("No read permission for $titleString", 'titleaccessdenied');
601 $linkBatch->addObj($titleObj);
604 // Make sure we remember the original title that was given to us
605 // This way the caller can correlate new titles with the originally requested,
606 // i.e. namespace is localized or capitalization is different
607 if (is_string($title) && $title !== $titleObj->getPrefixedText()) {
608 $this->mNormalizedTitles
[$title] = $titleObj->getPrefixedText();
615 protected function getAllowedParams() {
618 ApiBase
:: PARAM_ISMULTI
=> true
621 ApiBase
:: PARAM_TYPE
=> 'integer',
622 ApiBase
:: PARAM_ISMULTI
=> true
625 ApiBase
:: PARAM_TYPE
=> 'integer',
626 ApiBase
:: PARAM_ISMULTI
=> true
631 protected function getParamDescription() {
633 'titles' => 'A list of titles to work on',
634 'pageids' => 'A list of page IDs to work on',
635 'revids' => 'A list of revision IDs to work on'
639 public function getVersion() {
640 return __CLASS__
. ': $Id$';